#include "BLogFile.h"

using namespace blueberry;



#include <string.h>
#include <time.h>
#include <sys/time.h>
BLogger::BLogger(const char * _zFilename, Byte _btLogLevel, bool _bIsNewfile)
{
	strcpy(z_Filename, _zFilename);
	if ( _bIsNewfile )
	{
		fp_Logger = fopen(z_Filename,"w");
		logInfo(0, "New log file created");
	}
	else
	{
		fp_Logger = fopen(z_Filename, "a");
		logInfo(0,"Log file appended");
	}
	bt_LogLevel = _btLogLevel;
}

BLogger::~BLogger()
{
	if ( fp_Logger )
		fclose(fp_Logger);
	fp_Logger = NULL;
}

void BLogger::logInfo(Byte _btLogLevel,const char * _zInfo, ...)
{
	if ( _btLogLevel > bt_LogLevel)
		return;

	setTimestamp();
	UInt uiLen = BLOG_TS_BUFFER_SIZE;

	va_list ap;
	va_start(ap, _zInfo);
	int iBufLen = vsnprintf(z_LogBuffer + BLOG_TS_BUFFER_SIZE, BLOG_MAX_LOGINFO_SIZE, _zInfo, ap);
	va_end(ap);

	uiLen += iBufLen;
	z_LogBuffer[uiLen++] = '\n';
	fwrite(z_LogBuffer,1, uiLen, fp_Logger);
}

void BLogger::setTimestamp()
{
	struct timeval tv;
	gettimeofday(&tv, NULL);
	time_t uiSec = (UInt)tv.tv_sec;
	if ( uiSec != ui_LastSecond )
	{
		struct tm * timeinfo;
		timeinfo = localtime(&(uiSec));
		ui_LastTSBufPos = sprintf(z_LogBuffer,"[%d-%02d-%02d %02d:%02d:%02d.%06d] ", timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec, tv.tv_usec);
		ui_LastTSBufPos -= 8;
		ui_LastSecond = uiSec;
	}
	else
	{
		sprintf(z_LogBuffer + ui_LastTSBufPos,"%06d] ", tv.tv_usec);
	}
}
